import { create } from 'zustand'
import { setStorage, getStorage } from '@/utils/storage'
import type { userType } from '@/types'

interface userInfoStore {
  userInfo: userType | null,
  updateUserInfo: (userInfo: userType) => void;
}

const localData = getStorage('user-info') as userType

const defautUserInfo: userType = {
  id: undefined,
  username: '',
  token: ''
}
const userInfoInit: userType = localData?.id ? localData : defautUserInfo
const useuserInfoStore = create<userInfoStore>()((set) => ({
  userInfo: userInfoInit,
  updateUserInfo: (data: userType) => {
    set(() => {
      const userInfoData = {
        ...data,
        permissionCodes: (data?.permissionCode || '').split(',')
      }
      setStorage('user-info', userInfoData)
      return {
        userInfo: userInfoData
      }
    })
  }
}))

export default useuserInfoStore